package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Member;
import com.itheima.health.pojo.User;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 登录控制器
 */
@RestController
@RequestMapping("/mobile/login")
@Slf4j
public class MobileLoginController {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MemberService memberService;

    @PostMapping("/smsLogin")
    public Result login(@RequestBody Map map, HttpSession session){
        String telephone = map.get("telephone").toString();
        String validateCode = map.get("validateCode").toString();

        log.info("用户开始登录");
        //从redis中获取验证码
        Object codeInRedis = redisTemplate.opsForValue().get(RedisConst.VALIDATE_CODE_PREFIX + "MOBILE_SIGNIN:" + telephone);

        //验证码进行比对
        if(codeInRedis != null && codeInRedis.equals(validateCode)){
            //登录成功,删除验证码
            redisTemplate.delete(RedisConst.VALIDATE_CODE_PREFIX + "MOBILE_SIGNIN:" + telephone);

            //比对成功
            //隐藏业务 登录及注册
            //如果数据库中有此用户,什么都不做;
            Member member = memberService.selectByTelephone(telephone);

            //如果没有,保存到数据库中
            if(member == null){
                member = new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                memberService.save(member);
            }
            //登录之后,将用户信息存在session中 再次访问时,不用重复登录
            session.setAttribute("member",member.getId());
            //过滤器中加 手机端 登录校验
            return new Result(true,MessageConst.LOGIN_SUCCESS);

        }
        return new Result(false,MessageConst.LOGIN_FAIL);
    }
}
